<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" v-model="queryParams.keyword" @input ="changeValue()"/>
        <!-- 树形组件 -->
        <el-tree ref ='deptTree'
                 node-key="id"
                 :data="depts"
                 :props="defaultProps"
                  default-expand-all
                  highlight-current
                 :expand-on-click-node = "false"
                 @current-change="selectNode"
        ></el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="addEmployee">添加员工</el-button>
          <el-button size="mini" @click="changeDialog">excel导入</el-button>
          <el-button size="mini" @click="importExcle">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
              <el-table-column prop="staffPhoto" align="center" label="头像" >
                <template v-slot="{row}">
                  <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
                  <span v-else class="username">{{ row.username?.charAt(0) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="username" label="姓名" />
              <el-table-column prop="mobile" label="手机号" sortable />
              <el-table-column prop="workNumber" label="工号" sortable />
              <el-table-column prop="formOfEmployment" label="聘用形式">
                <template v-slot="{row}">
                  <!-- 1:表示正式 2:表示非正式 -->
                  <span>{{row.formOfEmployment === 1 ?'正式':row.formOfEmployment===2?'非正式':'无'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="departmentName" label="部门" />
              <el-table-column prop="timeOfEntry" label="入职时间" sortable />
              <el-table-column label="操作" width="280px">
                    <template v-slot="{row}">
                        <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
                        <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
                        <el-popconfirm title="确认删除该行数据吗？"  @onConfirm="deleteEmployee(row.id)">
                          <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
                        </el-popconfirm>
                    </template>
              </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row style="height: 60px" align="middle" type="flex" justify="end">
              <el-pagination
                  layout="total,prev, pager, next"
                  :total="total"
                  :page-size="queryParams.pagesize"
                  :current-page = "queryParams.page"
                  @current-change ='changePage'
              />
          </el-row>
      </div>
    </div>
    <!-- 导入excle表 -->
    <ImportExcle :showExcelDialog.sync="showExcelDialog" :uploadSuccess="getEmployeeList"></ImportExcle>
    <!-- 角色弹框 -->
    <el-dialog :visible.sync="showRoleDialog" >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList " :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
        <el-row style="margin: 10px;">
          <el-col type="flex" align="middle" justify="center">
            <el-button type="primary" @click="btnOk">确实</el-button>
            <el-button @click="btnCenter">取消</el-button>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </el-dialog>
  </div>
</template>

<script>
import {getDepartment} from '@/api/department'
import {transListToTreeData} from '@/utils'
import {getEmployeeList,importExcle,deleteEmployee,getEnableRoleList, assignRole,getEmployeeById} from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcle from './components/import-excel.vue'
export default {
  name: 'Employee',
  components:{
    ImportExcle
  },
  //数据
  data(){
    return{
      //树结构的数据
      depts:[],
      defaultProps:{
        children: 'children',
        label: 'name'
      },
      //table的查询条件
      queryParams:{
        departmentId: null,
        page:1,
        pagesize:5,
        keyword:''
      },
      //table的总数
      total:0,
      //table查询的数据列表
      tableData:[],
      //控制导入弹框的按钮
      showExcelDialog:false,
      //控制角色的弹框按钮
      showRoleDialog:false,
      //角色列表
      roleList:[],
      //角色绑定的数据
      roleIds: [],
      currentUserId: null
    }
  },
  //方法
  methods:{
    //部门数据
    async getDepartment(){
      this.depts = transListToTreeData(await getDepartment(),0)
      this.queryParams.departmentId =this.depts[0].id
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    //监听树节点的变化
    selectNode(node){
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    //获取员工列表
    async getEmployeeList(){
     const {rows,total} =  await getEmployeeList(this.queryParams)
     this.tableData =rows
     this.total = total
    },
    //页面改变
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    },
    //搜索框值发生改变的时候调用的函数
    changeValue(){
      //防抖处理
      clearTimeout(this.timer)
      this.timer = setTimeout(()=>{
        this.queryParams.page=1
        this.getEmployeeList()
      },300)
    },
    //导出excle表格
    async importExcle(){
      const result =await importExcle()
      FileSaver.saveAs(result,'员工信息表.xlsx')
    },
    //导入弹窗的方法
    changeDialog(){
      this.showExcelDialog = true
    },
    //删除员工
    async deleteEmployee(id){
      await deleteEmployee(id)
      if(this.tableData.length===1 && this.queryParams.page>1){
          this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    //点击添加跳转页面
    addEmployee(){
      this.$router.push('/employee/detail')
    },
    //分配角色
    async btnRole(id){
      this.showRoleDialog = true
      this.roleList = await getEnableRoleList()
      this.currentUserId = id
      const {roleIds} = await getEmployeeById(id)
      this.roleIds =roleIds
    },
    //角色确认按钮
    async btnOk(){
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds  
      })
      this.$message.success('添加成功')
      this.btnCenter()
    },
    btnCenter(){
      this.showRoleDialog =false
    }
  },
  created() {
    this.getDepartment()
   
  },


}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>